<?php

namespace app\factory\wxPay;

use app\libs\Oss;
use app\libs\Util;
use OSS\Core\OssException;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;

class WxParam
{//微信配置信息

    private $xcx_appid = "";//小程序appID
    private $mch_id = "";//商户号
    private $key = "";//api秘钥
    private $secret = "";//小程序唯一凭证密钥

    public function __construct()
    {
        $this->xcx_appid = Config::get('system.wx_pay.app_id');//小程序id
        $this->mch_id = Config::get('system.wx_pay.mch_id');//获取小程序mch_id
        $this->key = Config::get('system.wx_pay.key');//获取小程序key
        $this->secret = Config::get('system.wx_weapp.secret');//获取小程序唯一凭证密钥
    }

    //获取小程序appid
    public function get_xcx_appid()
    {
        return $this->xcx_appid;
    }

    //获取小程序mch_id
    public function get_mch_id()
    {
        return $this->mch_id;
    }

    //获取小程序key
    public function get_key()
    {
        return $this->key;
    }

    //获取小程序secret
    public function get_secret()
    {
        return $this->secret;
    }

    //获取access_token
    public function get_access_token()
    {
        $redis = Cache::store('redis')->handler();
        $redis_key = 'panggua:';
        $exist = $redis->get($redis_key . "wx_access_token");
        if (!$exist) {
            $url = "https://api.weixin.qq.com/cgi-bin/token";
            $data['grant_type'] = "client_credential";
            $data['appid'] = $this->xcx_appid;//小程序id
            $data['secret'] = $this->secret;//秘钥
            $res = Util::get_request($url, $data);
            $res = json_decode($res, true);
            if (!isset($res['access_token'])) {
                return false;
            }
            $redis->set($redis_key . "wx_access_token", $res['access_token'], 5000);//微信access_token有效期7200  存7000
        }
        $wx_access_token = $redis->get($redis_key . "wx_access_token");
        return $wx_access_token;
    }

    /**
     * 获取带参数的微信小程序二维码
     * @param string $scene
     * @param string $page
     * @param int $width
     * @return string
     */
    public function getSceneQrcode($scene = "", $page = "", $width = 280)
    {
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;//access_token;
        $data['scene'] = "index";
        $data['width'] = $width;
        if ($scene != "") {
            $data['scene'] = $scene;//参数
        }
        if ($page != "") {
            $data['page'] = $page;//跳转参数url
        }
        $res = Util::post_request($url, json_encode($data));
        $url = "./goods_img/promote_code/" . $data['scene'] . ".png";
        $ret = file_put_contents($url, $res, true);
        return $url;
    }
}